function KinectDevice() {}

KinectDevice.DEPTH = 0
KinectDevice.COLOR = 1

KinectDevice.JOINTS_NAME = [["head","shouldercenter"],["shouldercenter","shoulderright"],["shouldercenter","shoulderleft"],["shoulderright","elbowright"],
       ["shoulderleft","elbowleft"],["elbowright","wristright"],["elbowleft","wristleft"],["wristright","handright"],["wristleft","handleft"],
       ["shouldercenter","spine"],["spine","hipcenter"],["hipcenter","hipright"],["hipcenter","hipleft"],["hipright","kneeright"],
       ["hipleft","kneeleft"],["kneeright","ankleright"],["kneeleft","ankleleft"],["ankleright","footright"],["ankleleft","footleft"]]


KinectDevice.initialise = () => {
  KinectDevice.socket = new WebSocket("ws://127.0.0.1:8181")
  KinectDevice.connected = false

  KinectDevice.skeletons = []

  KinectDevice.data = []
  KinectDevice.cameraData = null

  KinectDevice.socket.onopen = () => {
    KinectDevice.connected = true
  }

  KinectDevice.socket.onclose = () => {
    KinectDevice.connected = false
  }

  KinectDevice.socket.onmessage = (e) => {
    if (typeof e.data === "string") {
      var jsonobject = JSON.parse(e.data)
      KinectDevice.data = jsonobject.skeletons

      KinectDevice.updateSkeletons()
    } else if (e.data instanceof Blob) {
      var blob = e.data
      // TODO: Create Three.JS texture with data
    }
  }

  KinectDevice.debugScene = new THREE.Scene()
  var point = new THREE.Vector3(0, 0, 0)
  for (var i = 0; i < 19; i++) {
    KinectDevice.debugScene.add(KinectDevice.createCylinderBetweenPoints(point, point))
  }
}

KinectDevice.isConnected = () => {
  return KinectDevice.connected
}

KinectDevice.updateSkeletons = () => {
  for (var k = 0; k < KinectDevice.data.length; k++) {
    if (KinectDevice.skeletons[k] === undefined) {
      KinectDevice.skeletons[k] = new Skeleton()
      KinectDevice.skeletons[k].createJoints(KinectDevice.JOINTS_NAME)
    }

    KinectDevice.skeletons[k].updateJoints(KinectDevice.data[k].joints)
  }
}

KinectDevice.updateDebugSkeleton = (joints) => {
}

KinectDevice.createCylinderBetweenPoints = (a, b) => {
   var dist = Math.sqrt(Math.pow((a.x - b.x),2) + Math.pow((a.y - b.y),2) + Math.pow((a.z - b.z),2))

   var geometry = new THREE.CylinderGeometry(0.1, 0.1, dist, 16, 32, false)
   var material = new THREE.MeshPhongMaterial({color: 0xff0000})
   var cylinder = new THREE.Mesh(geometry, material)
   cylinder.position.set(0, dist/2, 0)

   var obj = new THREE.Object3D()
   obj.position.set(a.x, a.y, a.z)
   obj.add(cylinder)
   obj.lookAt(b)

   return obj
}

KinectDevice.setCameraMode = (mode) => {
  if (mode === KinectDevice.COLOR) {
    socket.send("Color")
  } else if (mode === KinectDevice.DEPTH) {
    socket.send("Depth")
  }
}
